﻿using System.IO;
using System.Text;
using Newtonsoft.Json;

namespace QuickShare.Vsix.SqlList.Commons
{
    public static class Helper
    {
        public static string FormatJson(string json)
        {
            if(!string.IsNullOrWhiteSpace(json))
            {
                json = json.Replace("[", "[\r\n\t")
                    .Replace(",{", ",\r\n\t{")
                    .Replace("]", "\r\n]")
                    .Replace("{", "{ ")
                    .Replace("}", " }")
                    .Replace(",\"", ", \"")
                    .Replace("\\", "/")
                    .Replace("//", "/");
                return json;
            }
            return json;
        }
        public static bool IsReadonly(string path)
        {
            if(File.Exists(path))
            {
                var attrs = File.GetAttributes(path);
                return attrs.HasFlag(FileAttributes.ReadOnly);
            }
            return false;
        }
        public static void RemoveReadonly(string path)
        {
            if(File.Exists(path))
            {
                var attrs = File.GetAttributes(path);
                if(attrs.HasFlag(FileAttributes.ReadOnly))
                {
                    attrs = attrs & ~FileAttributes.ReadOnly;
                    File.SetAttributes(path, attrs);
                }
            }
        }

        public static void TryCreateDir(string path)
        {
            if(!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }

        public static T TryParseFromJson<T>(string jsonString)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(jsonString);
            }
            catch
            {
                return default;
            }
        }
        /// <summary> 
        /// 通过给定的文件流，判断文件的编码类型 
        /// </summary> 
        /// <param name="fileName">文件流</param> 
        /// <returns>文件的编码类型</returns> 
        public static Encoding GetEncoding(string fileName)
        {
            //byte[] Unicode = new byte[] { 0xFF, 0xFE };
            //byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF };
            //byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //带BOM 
            var encoding = Encoding.Default;
            using(var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                using(BinaryReader r = new BinaryReader(fs, encoding))
                {
                    int i;
                    int.TryParse(fs.Length.ToString(), out i);
                    byte[] ss = r.ReadBytes(i);
                    if((ss.Length > 3 && ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF) || IsUTF8Bytes(ss))
                    {
                        encoding = Encoding.UTF8;
                    }
                    else if(ss.Length > 3 && ss[0] == 0xFE && ss[1] == 0xFF)
                    {
                        encoding = Encoding.BigEndianUnicode;
                    }
                    else if(ss.Length > 3 && ss[0] == 0xFF && ss[1] == 0xFE)
                    {
                        encoding = Encoding.Unicode;
                    }
                }
            }
            return encoding;
        }

        /// <summary> 
        /// 判断是否是不带 BOM 的 UTF8 格式 
        /// </summary> 
        /// <param name="data"></param> 
        /// <returns></returns> 
        private static bool IsUTF8Bytes(byte[] data)
        {
            int charByteCounter = 1; //计算当前正分析的字符应还有的字节数 
            byte curByte; //当前分析的字节. 
            for(int i = 0; i < data.Length; i++)
            {
                curByte = data[i];
                if(charByteCounter == 1)
                {
                    if(curByte >= 0x80)
                    {
                        //判断当前 
                        while(((curByte <<= 1) & 0x80) != 0)
                        {
                            charByteCounter++;
                        }
                        //标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X 
                        if(charByteCounter == 1 || charByteCounter > 6)
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    //若是UTF-8 此时第一位必须为1 
                    if((curByte & 0xC0) != 0x80)
                    {
                        return false;
                    }
                    charByteCounter--;
                }
            }
            if(charByteCounter > 1)
            {
                return false;
            }
            return true;
        }


    }
}
